package platform.nio;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class ChannelHandler {
    SocketChannel socketChannel;
    Charset charset;

    public ChannelHandler(SocketChannel socketChannel, Charset charset) {
        this.socketChannel = socketChannel;
        this.charset = charset;
    }


    public void writeAndFlush(Object msg) {

        try {
            byte[] bytes = msg.toString().getBytes(charset);
            ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
            byteBuffer.put(bytes);
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public SocketChannel socketChannel(){
        return socketChannel;
    }

    public SocketChannel channel() {
        return socketChannel;
    }
}
